package cn.phecda.boot.data.mybatis.support;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.NonNull;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p> 基础服务, 支持Spring Data分页查询方法 </p>
 *
 * @author : wanpinwei
 */
public abstract class CommonMybatisService<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {
    @NonNull
    public Optional<T> findById(@NonNull Serializable id) {
        return Optional.ofNullable(getBaseMapper().selectById(id));
    }

    /**
     * 集成Spring Data分页
     * @param wrapper 包装器
     * @param pageable 分页
     * @return 分页数据
     */
    public Page<T> findPage(Wrapper<T> wrapper, Pageable pageable) {
        IPage<T> page = getBaseMapper().selectPage(PageAdapter.of(pageable), wrapper);
        return PageAdapter.of(page);
    }

    public Page<Map<String, Object>> findMapsPage(Wrapper<T> wrapper, Pageable pageable) {
        IPage<Map<String, Object>> page = getBaseMapper().selectMapsPage(PageAdapter.of(pageable), wrapper);
        return PageAdapter.of(page);
    }

    public List<T> findList(Wrapper<T> wrapper, Pageable pageable) {
        return getBaseMapper().selectList(PageAdapter.of(pageable), wrapper);
    }
}
